<template>
  <el-main>
    <div class="mt-4">
      <el-row>
        <el-col :span="12">
          <el-input

              v-model="search"
              class="input-with-select"
                placeholder="请输入记录编号"
              @input="fetchData"
          >
<!--            <template #append>-->
<!--              <el-button icon="Search" @click="history">搜索</el-button>-->
<!--            </template>-->
          </el-input>
        </el-col>
        <el-col :span="8"></el-col>
        <el-button type="danger" @click="handleBatchDelete">批量删除</el-button>
      </el-row>
      <el-row></el-row>
    </div>
    <el-row>
      <form @submit.prevent="history">
        <el-table :data="tableData" class="table" border @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="preId" label="记录编号" width="160" />
          <el-table-column prop="time" label="预交时间" width="160" />
          <el-table-column prop="pay" label="预交费用" width="200" />
          <el-table-column prop="prepayment" label="交前余额" width="160" />
          <el-table-column prop="balance" label="交后余额" width="160" />
          <el-table-column prop="type" label="支付方式" width="160" />
          <el-table-column label="操作" width="120">
            <template #default="scope">
              <el-button type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </form>
    </el-row>

    <el-row class="center">
      <el-button mb-2 @click="toggle" class="tranlate">Switch Language</el-button>
      <br />
      <el-config-provider :locale="locale">
        <el-col>
          <el-pagination
              background
              class="pagination"
              layout="prev, pager, next, jumper"
              :total="total"
              :current-page="currentPage"
              :page-size="pageSize"
              @current-change="handlePageChange"
          />
        </el-col>
      </el-config-provider>
    </el-row>
  </el-main>
</template>

<script lang="ts" setup>
import { ref, reactive, defineComponent, onMounted } from 'vue'
import { Search, Document, Location, Setting } from '@element-plus/icons-vue'
import { computed } from 'vue'
import axios from "axios";
import { useRouter } from "vue-router";
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import en from 'element-plus/dist/locale/en.mjs'
import { TypedArrayUtils } from "three/examples/jsm/utils/TypedArrayUtils";
import size = TypedArrayUtils.Kdtree.BinaryHeap.size;

interface User {
  preId: string
  prepayment: string
  balance: string
  type: string
  time: string
  pay: string
  electrical_price: string
}

const tableData = ref<User[]>([]);
const currentPage = ref(1);
const total = ref(0);
const selectedRows = ref<User[]>([]);
const router = useRouter()
let data = reactive({
  history: {
    electrical_price: '',
    preId: '',
    time: '',
    pay: '',
    prepayment: '',
    balance: '',
    type: '',
  },
  historys: [] as User[]
})

const fetchhistorys = async () => {
  try {
    const response = await axios.get('http://localhost:8080/history');
    data.historys = response.data;
  } catch (error) {
    console.error('Error fetching water prices:', error);
  }
}

const input2 = ref('')
const search = ref('')
const pageSize = ref(7); // 每页显示10条数据

const fetchData = async () => {
  const user = JSON.parse(localStorage.getItem('user') || '{}');
  const userId = user.userId;

  if (!userId) {
    console.error('User ID not found in local storage');
    return;
  }

  try {
    const response = await axios.get("http://localhost:8080/history/list", {
      params: {
        page: currentPage.value,
        size: pageSize.value,
        search: search.value,
        userId: userId,
      },
    });
    tableData.value = response.data.data.records;
    total.value = response.data.data.total; // 设置总数
  } catch (error) {
    console.error("Failed to fetch data:", error);
  }
};

const handlePageChange = (page: number) => {
  currentPage.value = page;
  fetchData();
};

const handleSelectionChange = (selection: User[]) => {
  selectedRows.value = selection;
};

const handleDelete = async (index: number, row: User) => {
  try {
    const response = await axios.post("http://localhost:8080/history/noticeDelete", { ids: [row.preId] });
    if (response.status === 200) {
      console.log(`Deleted row with id: ${row.preId}`);
      fetchData(); // 删除后重新获取数据
    } else {
      console.error("Failed to delete data:", response.data);
    }
  } catch (error) {
    console.error("Failed to delete data:", error);
  }
};

const handleBatchDelete = async () => {
  const ids = selectedRows.value.map((row) => row.preId);
  if (ids.length === 0) {
    alert("请选择要删除的通知");
    return;
  }
  try {
    const response = await axios.post("http://localhost:8080/history/noticeDelete", { ids });
    if (response.status === 200) {
      console.log(`Deleted rows with ids: ${ids}`);
      fetchData(); // 批量删除后重新获取数据
    } else {
      console.error("Failed to delete data:", response.data);
    }
  } catch (error) {
    console.error("Failed to delete data:", error);
  }
};

const toggle = () => {
  language.value = language.value === 'zh-cn' ? 'en' : 'zh-cn'
}

const language = ref('zh-cn')
const locale = computed(() => (language.value === 'zh-cn' ? zhCn : en))

onMounted(() => {
  let localUser = localStorage.getItem('user')
  if (localUser) {
    let data = JSON.parse(localUser)
    data.history = data
  }
  // 在组件挂载时调用获取数据的函数
  fetchData();
})
</script>

<style>
.input-with-select .el-input-group__prepend {
  background-color: var(--el-fill-color-blank);
}
.center {
  margin-top: 30px;
  margin-left: 300px;
}
.tranlate {
  display: none;
}
.table {
  width: 1175px;
  margin-left: 50px;
  margin-top: 20px;
}
.input-with-select{
  margin-left: 50px;
  width: 250px;
}
.pagination{
  margin-left: 180px;
}
</style>